package com.biwin.module.security.starter.handler;

import cn.hutool.json.JSONUtil;
import com.biwin.common.app.enums.BwSecurityExceptionEnum;
import com.biwin.common.app.vo.BwResponse;
import com.biwin.core.api.vo.OnlineUserInfoVo;
import com.biwin.module.org.api.service.ISystemUserService;
import com.biwin.module.security.api.vo.BwUserDetailVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Authentication success handler
 *
 * @author biwin
 * @since 0.0.1
 */
@Component
public class BwAuthenticationSuccessHandler implements AuthenticationSuccessHandler, ApplicationEventPublisherAware {

    private ApplicationEventPublisher applicationEventPublisher;

    @Autowired
    private ISystemUserService systemUserService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        BwUserDetailVo bwUserDetailVo = (BwUserDetailVo) authentication.getPrincipal();
        systemUserService.updateLoginDate(bwUserDetailVo.getSystemUserVo().getId());
        if (bwUserDetailVo.getSystemUserVo().getPasswordFaultNum() > 0) {
            systemUserService.updatePasswordFaultNum(bwUserDetailVo.getSystemUserVo().getId(), Integer.valueOf(0));
        }

        // applicationEventPublisher.publishEvent();  todo 添加登录日志
        // update user login log
        // or get user permissions

        OnlineUserInfoVo onlineUserInfoVo = new OnlineUserInfoVo();
        BeanUtils.copyProperties(bwUserDetailVo.getSystemUserVo(), onlineUserInfoVo, "password");
        onlineUserInfoVo.setToken(bwUserDetailVo.getToken());

        BwResponse bwResponse = BwResponse.response(BwSecurityExceptionEnum.USER_LOGIN_SUCCESS, onlineUserInfoVo);
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(JSONUtil.toJsonStr(bwResponse));
    }

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }
}
